import { MenuOutlined } from '@ant-design/icons';
import { Button, Form, Table, Switch, InputNumber, Select, Radio } from 'antd';
import { arrayMoveImmutable } from 'array-move';
import { SortableContainer, SortableElement, SortableHandle } from 'react-sortable-hoc';
import type { SortableContainerProps, SortEnd } from 'react-sortable-hoc';

import styles from './index.less';

const DragHandle = SortableHandle(() => <MenuOutlined style={{ cursor: 'grab', color: '#999' }} />);

const SortableItem = SortableElement((props: React.HTMLAttributes<HTMLTableRowElement>) => (
  <tr {...props} />
));
const SortableBody = SortableContainer((props: React.HTMLAttributes<HTMLTableSectionElement>) => (
  <tbody {...props} />
));

type Iprops = {
  mockStandardProducts: any[];
  dataSource: any[];
  setDataSource: (value: any) => void;
};

const DragTable: React.FC<Iprops> = ({ dataSource, setDataSource, mockStandardProducts }) => {
  const onSortEnd = ({ oldIndex, newIndex }: SortEnd) => {
    if (oldIndex !== newIndex) {
      const newData = arrayMoveImmutable(dataSource.slice(), oldIndex, newIndex).filter(
        (el: any) => !!el,
      );
      console.log('Sorted items: ', newData);
      setDataSource(newData);
    }
  };

  const DraggableContainer = (props: SortableContainerProps) => (
    <SortableBody
      useDragHandle
      disableAutoscroll
      // helperClass="row-dragging"
      helperClass={styles['row-dragging']}
      onSortEnd={onSortEnd}
      {...props}
    />
  );

  const DraggableBodyRow: React.FC<any> = ({ className, style, ...restProps }) => {
    // function findIndex base on Table rowKey props and should always be a right array index
    const index = dataSource.findIndex((x) => x.index === restProps['data-row-key']);
    return <SortableItem index={index} {...restProps} />;
  };

  const handleDelete = (key: any) => {
    setDataSource(dataSource.filter((item) => item.key !== key));
  };

  const columns: any = [
    {
      title: '',
      dataIndex: 'sort',
      width: 30,
      className: 'drag-visible',
      render: () => <DragHandle />,
    },
    {
      title: '序号',
      dataIndex: 'index',
      key: 'index',
      sorter: (a: any, b: any) => a.index - b.index,
    },
    {
      title: '标准品',
      dataIndex: 'standardProduct',
      key: 'standardProduct',
      render: (_: any, record: any) => (
        <Form.Item
          name={[`${0}`, 'list', `${record.key}`, 'standardProduct']}
          rules={[{ required: true, message: '必填' }]}
          noStyle
        >
          <Select
            style={{ width: '100%' }}
            placeholder="选择标准品"
            options={mockStandardProducts}
          />
        </Form.Item>
      ),
    },
    {
      title: '是否默认选中',
      dataIndex: 'isDefault',
      key: 'isDefault',
      render: (text: any, record: any) => (
        <Form.Item name={[`${0}`, 'list', `${record.key}`, 'isDefault']} noStyle>
          <Switch />
        </Form.Item>
      ),
    },
    {
      title: '是否隐藏',
      dataIndex: 'isHidden',
      key: 'isHidden',
      render: (text: any, record: any) => (
        <Form.Item name={[`${0}`, 'list', `${record.key}`, 'isHidden']} noStyle>
          <Switch />
        </Form.Item>
      ),
    },
    {
      title: () => {
        return (
          <Form.Item name={[`${0}`, 'chajia']} noStyle>
            <Radio.Group
              optionType="button"
              options={[
                { label: '手动差价', value: 'manual' },
                { label: '自动差价', value: 'auto' },
              ]}
            />
          </Form.Item>
        );
      },
      dataIndex: 'priceType',
      key: 'priceType',
      render: (text: any, record: any) => (
        <Form.Item name={[`${0}`, 'list', `${record.key}`, 'priceType']} noStyle>
          <InputNumber style={{ width: '100%' }} step={1} />
        </Form.Item>
      ),
    },
    {
      title: '数量上限',
      width: 200,
      dataIndex: 'quantityLimit',
      key: 'quantityLimit',
      render: (text: any, record: any) => (
        <Form.Item name={[`${0}`, 'list', `${record.key}`, 'quantityLimit']} noStyle>
          <InputNumber style={{ width: '100%' }} step={1} />
        </Form.Item>
      ),
    },
    {
      title: '备键',
      dataIndex: 'remark',
      key: 'remark',
      render: () => (
        <Button type="link" onClick={() => {}}>
          查看
        </Button>
      ),
    },
    {
      title: '操作',
      dataIndex: 'operation',
      key: 'operation',
      render: (text: any, record: any) => (
        <Button type="link" onClick={() => handleDelete(record.key)}>
          删除
        </Button>
      ),
    },
  ];

  return (
    <Table
      pagination={false}
      dataSource={dataSource}
      columns={columns}
      // rowKey="id"
      rowKey="index"
      // DraggableBodyRow----依赖于index
      components={{
        body: {
          wrapper: DraggableContainer,
          row: DraggableBodyRow,
        },
      }}
    />
  );
};

export default DragTable;
